import { defineStore } from 'pinia';
import defaultSettings from '@/settings';

const {
  themeColor,
  sideTheme,
  showSettings,
  topNav,
  sortView,
  tagsView,
  fixedHeader,
  sidebarLogo,
  showMenuText,
  dynamicTitle,
  siteMap,
  portalNoticeBox,
  fontSize,
  fileLinkShow,
  topNavLeft
} = defaultSettings;

let storageSetting = {};
try {
  storageSetting = JSON.parse(localStorage.getItem('layout-setting')) || {};
} catch (err) {
  storageSetting = {};
}

export const useSettingsStore = defineStore('settings', {
  state: () => ({
    title: '',
    theme: storageSetting.theme || themeColor || '#409EFF',
    sideTheme: storageSetting.sideTheme || sideTheme,
    showSettings: showSettings,
    topNav: storageSetting.topNav === undefined ? topNav : storageSetting.topNav,
    portalNoticeBox: storageSetting.portalNoticeBox === undefined ? (portalNoticeBox || false) : storageSetting.portalNoticeBox,
    tagsView: storageSetting.tagsView === undefined ? tagsView : storageSetting.tagsView,
    topNavLeft: storageSetting.topNavLeft || topNavLeft,
    siteMap: storageSetting.siteMap === undefined ? (siteMap || false) : storageSetting.siteMap,
    fixedHeader: storageSetting.fixedHeader === undefined ? fixedHeader : storageSetting.fixedHeader,
    sidebarLogo: storageSetting.sidebarLogo === undefined ? sidebarLogo : storageSetting.sidebarLogo,
    showMenuText: storageSetting.showMenuText === undefined ? showMenuText : storageSetting.showMenuText,
    dynamicTitle: storageSetting.dynamicTitle === undefined ? dynamicTitle : storageSetting.dynamicTitle,
    fontSize: storageSetting.fontSize === undefined ? fontSize : storageSetting.fontSize,
    fileLinkShow: storageSetting.fileLinkShow === undefined ? fileLinkShow : storageSetting.fileLinkShow,
    sortView: storageSetting.sortView === undefined ? sortView : storageSetting.sortView
  }),
  actions: {
    changeSetting({ key, value }) {
      if (this.hasOwnProperty(key)) {
        this[key] = value;
        // 同步更新 localStorage
        localStorage.setItem('layout-setting', JSON.stringify({
          ...storageSetting,
          [key]: value
        }));
      }
    },
    setTitle(title) {
      this.title = title;
    }
  }
});